#!/bin/bash
#
# This script allows you to monitor if our internet link
# is up or not, and will collect the state changes into
# log file, for report activity link later.
#

# ---------------------------------------------------------
#   Load and check the configuration
# ---------------------------------------------------------

  # Load config file
  ConfigFile=/usr/local/TECNOQUIA/etc/dynIP.cfg
  if [ ! -e $ConfigFile ] || [ ! -r $ConfigFile ]
  then
     echo "ERROR: I can't read the config file [$ConfigFile]" >&2
     exit 5
  fi
  . $ConfigFile
    
  
  # Check the directory that i must save the log files
  BaseDir=$DIRECTORY_LOG
  if [ ! -w $BaseDir ]
  then
     echo "ERROR: I can't write into [$BaseDir]. Check that exists and the permissions on this directory" >&2
     exit 6
  fi
 

  # File with the activity internet link 
  logFile=$BaseDir/internet_link_status.log

  # Initial status will be DOWN
  LinkStatus=1



# ---------------------------------------------------------
#   Functions
# ---------------------------------------------------------

check_ping() {
   for ip in $IP_CHECK_LIST
   do
      ping -c 1 $ip >/dev/null 2>&1  && return 0
   done
   return 1
}



# ---------------------------------------------------------
#   M A I N
# ---------------------------------------------------------

  # Write our proccess pid into file
  echo $$ > /var/run/`basename $0`.pid

  # Trap exit signal
  trap "echo \"[`date "+%d/%h/%y  %H:%M:%S"`] [`date '+%s'`] Stop daemon `basename $0`\" >> $logFile; exit 0" SIGINT SIGTERM

  # Initialize the activity log 
  echo "[`date "+%d/%h/%y  %H:%M:%S"`] [`date '+%s'`] The daemon starts `basename $0`" >> $logFile

  # until the end of the world ... do...
  while [ true ]
  do
     # Check the ping...
     if check_ping 
     then
        # There ping , the ping replies ... It was down before ? 
        if [ $LinkStatus -eq 1 ]
        then
           # Yes, before it was down: The link has changed, from DOWN to UP
           echo "[`date "+%d/%h/%y  %H:%M:%S"`] [`date '+%s'`] The internet link is UP" >> $logFile
           # OK... we change the link state
           LinkStatus=0

           # Renew my public IP into dyndns
           /usr/local/TECNOQUIA/bin/renew_ip_dyndns  >/dev/null  2>&1
        fi
     else
        # Ups , we haven't ping replies ... it was up before?
        if  [ $LinkStatus -eq 0 ]
        then
           # Yes, before it was up: The link has changed, from UP to DOWN
           echo "[`date "+%d/%h/%y  %H:%M:%S"`] [`date '+%s'`] The internet link is DOWN" >> $logFile
           # OK... i need change del link state to DOWN
           LinkStatus=1
        fi
     fi
     
     # Sleep and wait 
     sleep 30s
  done

  exit 0
